/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package montecarlo.math;

import java.util.Random;

/**
 *
 * @author alucard
 */
public class monteCarloWorker extends Thread
{

    private double St, Drift, vSqrdt, X;
    private double T;
    private double r;
    private int nSteps, z, nSimulations, nbThread;
    private Random rand;
    private monteCarloHolder mtHolder;

    public monteCarloWorker(double St, double Drift, double vSqrdt, int z, int nSteps, int nSimulations, double X, int nbThread, double r, double T, Random rand, String name, monteCarloHolder mtHolder)
    {
        super(name);
        this.St = St;
        this.Drift = Drift;
        this.vSqrdt = vSqrdt;
        this.z = z;
        this.nSteps = nSteps;
        this.nSimulations = nSimulations;
        this.r = r;
        this.T = T;
        this.rand = rand;
        this.mtHolder = mtHolder;
        this.nbThread = nbThread;
        this.X = X;
    }

    @Override
    public void run()
    {
        double percent;
        double stLocal = 0, sum = 0;
        int i, j;
        for (i = 1; i < this.nSimulations; i++)
        {
            stLocal = this.St;
            for (j = 1; j < this.nSteps; j++)
            {
                stLocal = stLocal * Math.exp(Drift + vSqrdt * this.rand.nextGaussian());
            }
            sum = sum + Math.max(this.z * (stLocal - this.X), 0);
            if (i % 1000 == 0)
            {
                percent = (Double.valueOf(i) / Double.valueOf(this.nSimulations)) * 100;
                mtHolder.setPercent(Integer.parseInt(this.getName()), percent);
            }
        }
        mtHolder.setSum(mtHolder.getSum() + sum);

        mtHolder.setNbFinished(mtHolder.getNbFinished() + 1);

        if (mtHolder.getNbFinished() == nbThread)
        {
            mtHolder.setFinaleSum(Math.exp(-this.r * this.T) * (mtHolder.getSum() / (nSimulations * nbThread)));
        }

    }
}
